import React, { useState } from 'react'
import { useEffect } from 'react'
import { useRef } from 'react'
import DocumentTitle from 'react-document-title'
import { useHistory, useParams } from 'react-router-dom'
import styled from 'styled-components'

import { getWxAcode, getShareData } from '@api'
import axios from 'axios'
import { _isDev } from '@api/config'


const ShareCanvas = (props) => {

    const params = useParams()
    const history = useHistory()
    const [shareData, setShareData] = useState({})

    const tempImg = useRef()
    const shareImg = useRef()
    const acode = useRef()
    const myCanvas = useRef()

    useEffect(() => {
        let hash = `hash=goodsdetail/${params.id}`
        let config = {
            appid: _isDev ? 'wxeaef65640a28d704' : 'wxb02d1cee9d232633',
            secret: _isDev ? '2ce25911a67c1c92c9940943ac676af6' : 'bf23d6385636525e5b08f38afd8070d7',
            scene: hash,
            page: 'pages/home-login/main',
            type: 0 // 0 Acode 1 QrCode
        }

        axios.all([getWxAcode(config), getShareData({ goodsid: params.id })]).then(axios.spread((res1, res2) => {
            let a = {}
            a.acode = res1
            a.data = res2.data
            a.img = 'https://res.lexiangpingou.cn/' + res2.data.goodsimg
            setShareData(a)

        }))
    }, [params])

    useEffect(() => {
        let drawing = myCanvas.current
        let img = tempImg.current
        // let url = 'https://img.pddpic.com/mms-material-img/2020-10-29/838066fd-e71a-4f55-8aab-b6e4b8728738.jpeg.a.jpeg'
        getBase64Img(shareData.img, img)

        if (drawing.getContext && shareData.img) {
            const { goodsname, oprice, sprice, unit } = shareData.data

            img.onload = function () {

                let context = setupCanvas(drawing)

                // 上部分画布
                context.fillStyle = 'rgba(255,255,255, .3)'
                context.fillRect(0, 0, Rpx(568), Rpx(450))
                context.fillStyle = "#474747"
                context.font = `bold ${Rpx(30)}px  PingFang SC`
                context.fillText('图片丢失', Rpx(225), Rpx(244))

                // 绘制image
                try {
                    context.drawImage(img, 0, 0, Rpx(568), Rpx(450))
                } catch (error) {
                    console.log(error)
                }

                // 下半部分画布
                context.fillStyle = "white"
                context.fillRect(0, Rpx(450), Rpx(568), Rpx(285))


                // 商品标题
                context.fillStyle = "#474747"
                context.font = `bold ${Rpx(24)}px  PingFang SC`
                context.textAlign = "start"
                context.textBaseline = 'top'
                context.textBaseline = "middle"
                textPrewrap(context, goodsname, Rpx(90), Rpx(492), 0, Rpx(490), 2)

                // 商品类型 
                context.fillStyle = '#CF292B'
                context.fillRect(Rpx(30), Rpx(478), Rpx(52), Rpx(26))

                context.font = `bold ${Rpx(18)}px  PingFang SC`
                context.fillStyle = "white"
                context.fillText('拼货', Rpx(38), Rpx(492))


                // 左下角 price 售价
                context.fillStyle = '#C1C1C1'
                context.font = `500 ${Rpx(22)}px PingFang-SC-Medium`
                // context.textAlign = "start"
                // context.textBaseline = 'bottom'
                context.fillText(`售价：￥${oprice}`, Rpx(30), Rpx(618))

                // 划线
                // 创建路径
                context.strokeStyle = "#c1c1c1"
                context.beginPath()
                context.moveTo(Rpx(30), Rpx(618))
                context.lineTo(Rpx(130), Rpx(618))
                context.stroke()

                // ￥
                context.fillStyle = '#ff762e'
                context.font = `500 ${Rpx(24)}px PingFang-SC-Medium`
                context.fillText('￥', Rpx(30), Rpx(660))

                // 8.00/件
                context.font = `bold ${Rpx(36)}px PingFang SC`
                let p_width = context.measureText(`${sprice}`).width
                context.fillText(`${sprice}`, Rpx(56), Rpx(658))
                let j_width = context.measureText(`/${unit}`).width
                context.fillText(`/${unit}`, Rpx(p_width + 60), Rpx(658))



                // 供应价 背景
                context.fillStyle = '#000'
                context.fillRect(Rpx(p_width + j_width + 65), Rpx(648), Rpx(68), Rpx(30))

                // 供应价 文字
                context.fillStyle = '#FDEB86'
                context.font = `bold ${Rpx(18)}px PingFang-SC`
                context.fillText('供应价', Rpx(p_width + j_width + 72), Rpx(664))

                context.strokeStyle = '#474747'
                context.drawImage(acode.current, Rpx(405), Rpx(570), Rpx(133), Rpx(133))
                // context.strokeRect(Rpx(5.34), Rpx(7.7), Rpx(1.71), Rpx(1.71))

                shareImg.current.src = drawing.toDataURL()

                myCanvas.current.style = 'display: none'

            }

        }
    }, [shareData])



    return (
        <>
            <DocumentTitle title={props.route.title} />
            <ShareCanvasStyle>
                <div className="goback"
                    onClick={e => {
                        history.goBack()
                    }}
                >
                    返回
                </div>

                <canvas ref={myCanvas}>  该环境不支持canvas </canvas>

                <img className="shareimg" src='' alt="" ref={shareImg} />
                <img src={shareData.acode} ref={acode} alt="" className="acode" />
                <img ref={tempImg} className="tempimg" src="" alt="" />
            </ShareCanvasStyle>
        </>

    )

    function drawBase64Image(img) {
        let canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        let ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, img.width, img.height)
        let dataURL = canvas.toDataURL('image/png')
        return dataURL
    }
    function getBase64Img(url, ref) {

        let image = new Image()
        image.src = url + '?v=' + Math.random()  //处理缓存
        image.crossOrigin = "*"
        image.onload = function () {
            let base64 = drawBase64Image(image)
            ref.src = base64
        }
    }


    function setupCanvas(canvas) {

        // 创建一个两倍于实际大小的 canvas ， 然后用css 样式把canvas 限定在实际的大小。 

        // Get the device pixel ratio, falling back to 1.
        var dpr = window.devicePixelRatio || 1;
        // Get the size of the canvas in CSS pixels.
        var rect = canvas.getBoundingClientRect();
        // Give the canvas pixel dimensions of their CSS
        // size * the device pixel ratio.
        canvas.width = rect.width * dpr;
        canvas.height = rect.height * dpr;
        var ctx = canvas.getContext('2d');
        // Scale all drawing operations by the dpr, so you
        // don't have to worry about the difference.
        ctx.scale(dpr, dpr);
        return ctx;
    }

    function Rpx(n) {
        return n
    }

    /**
     * 
     * @param {*} ctx 画布的上下文环境
     * @param {*} content 需要绘制的文本内容
     * @param {*} drawX 绘制文本的x坐标
     * @param {*} drawY 绘制文本的y坐标
     * @param {*} lineHeight 文本之间的行高
     * @param {*} lineMaxWidth 每行文本的最大宽度
     * @param {*} lineNum 最多绘制的行数
     */
    function textPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
        var drawTxt = ''; // 当前绘制的内容
        var drawLine = 1; // 第几行开始绘制
        var drawIndex = 0; // 当前绘制内容的索引

        // 判断内容是否可以一行绘制完毕
        if (ctx.measureText(content).width <= lineMaxWidth) {
            ctx.fillText(content.substring(drawIndex, i), drawX, drawY);
        } else {
            for (var i = 0; i < content.length; i++) {
                drawTxt += content[i];
                if (ctx.measureText(drawTxt).width >= lineMaxWidth) {
                    if (drawLine >= lineNum) {
                        ctx.fillText(content.substring(drawIndex, i) + '..', drawX, drawY);
                        break;
                    } else {
                        ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
                        drawIndex = i + 1;
                        drawLine += 1;
                        drawY += lineHeight;
                        drawTxt = '';
                    }
                } else {
                    // 内容绘制完毕，但是剩下的内容宽度不到lineMaxWidth
                    if (i === content.length - 1) {
                        ctx.fillText(content.substring(drawIndex), drawX, drawY);
                    }
                }
            }
        }
    }
}
export default ShareCanvas
const ShareCanvasStyle = styled.div`

    text-align: center;
    box-sizing: border-box;
    padding: 2.09rem 1.21rem;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0,0,0, .3);

    .goback{
        width: .8rem;
        height: .8rem;
        border-radius: 50%;
        background-color: white;
        border: solid 1px white;
        position: fixed;
        line-height: .8rem;
        left: 1rem;
        top:  1rem;
    }


    .acode{
        display: none;
        width: 1.77rem;
        height: 1.77rem;
        border-radius: 50%;
    }

    .mask{
        position: absolute;
        width: 100vw;
        height: 100vh;
        background-color: rgba(0,0,0, .3)
    }

    canvas{
        width: 568px;
        height: 735px;
        opacity: 0;
    }

    .tempimg{
        width: 284px ;
        height: 225px;
        display: none;
    }

    .shareimg{
        width: 284px;
        height: 367.5px;
    }

`

